package com.jeesite.modules.customerclass.web;

import java.util.Map;
import java.util.List;

import com.jeesite.common.utils.OrgUtil;
import com.jeesite.modules.customerclass.entity.constant.CustomerClassConstant;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.config.Global;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.customerclass.entity.CustomerClass;
import com.jeesite.modules.customerclass.service.CustomerClassService;

/**
 * 客户分类Controller
 * @author 码脑洞
 * @version 2025-04-13
 */
@Controller
@RequestMapping(value = "${adminPath}/customerclass/customerClass")
public class CustomerClassController extends BaseController {

	@Autowired
	private CustomerClassService customerClassService;
	
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public CustomerClass get(Long autoId, boolean isNewRecord) {
		return customerClassService.get(autoId, isNewRecord);
	}

	/**
	 * 管理主页
	 */
	@RequiresPermissions("customerclass:customerClass:view")
	@RequestMapping(value = "index")
	public String index(CustomerClass customerClass, Model model) {
		model.addAttribute("customerClass", customerClass);
		return "modules/customerclass/customerClassIndex";
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("customerclass:customerClass:view")
	@RequestMapping(value = {"list", ""})
	public String list(CustomerClass customerClass, Model model) {
		model.addAttribute("customerClass", customerClass);
		return "modules/customerclass/customerClassList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("customerclass:customerClass:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public List<CustomerClass> listData(CustomerClass customerClass) {
		if (StringUtils.isBlank(customerClass.getParentCode())) {
			customerClass.setParentCode(CustomerClass.ROOT_CODE);
		}
		if (StringUtils.isNotBlank(customerClass.getCustomerClassCode())){
			customerClass.setParentCode(null);
		}
		if (StringUtils.isNotBlank(customerClass.getCustomerClassName())){
			customerClass.setParentCode(null);
		}
		List<CustomerClass> list = customerClassService.findList(customerClass);
		return list;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("customerclass:customerClass:view")
	@RequestMapping(value = "form")
	public String form(CustomerClass customerClass, Model model) {
		// 创建并初始化下一个节点信息
		customerClass = createNextNode(customerClass);
		if (OrgUtil.isValid()){
			customerClass.setOrgId(OrgUtil.getOrgId());
			customerClass.setOrgCode(OrgUtil.getOrgCode());
			customerClass.setOrgName(OrgUtil.getOrgName());
			customerClass.setSourceType(CustomerClassConstant.SOURCE_TYPE_MANUAL);
		}
		model.addAttribute("customerClass", customerClass);
		return "modules/customerclass/customerClassForm";
	}
	
	/**
	 * 创建并初始化下一个节点信息，如：排序号、默认值
	 */
	@RequiresPermissions("customerclass:customerClass:edit")
	@RequestMapping(value = "createNextNode")
	@ResponseBody
	public CustomerClass createNextNode(CustomerClass customerClass) {
		if (StringUtils.isNotBlank(customerClass.getParentCode())){
			customerClass.setParent(customerClassService.get(customerClass.getParentCode()));
		}
		if (customerClass.getIsNewRecord()) {
			CustomerClass where = new CustomerClass();
			where.setParentCode(customerClass.getParentCode());
			CustomerClass last = customerClassService.getLastByParentCode(where);
			// 获取到下级最后一个节点
			if (last != null){
				customerClass.setTreeSort(last.getTreeSort() + 30);
			}
		}
		// 以下设置表单默认数据
		if (customerClass.getTreeSort() == null){
			customerClass.setTreeSort(CustomerClass.DEFAULT_TREE_SORT);
		}
		return customerClass;
	}

	/**
	 * 保存数据
	 */
	@RequiresPermissions("customerclass:customerClass:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated CustomerClass customerClass) {
		customerClassService.save(customerClass);
		return renderResult(Global.TRUE, text("保存客户分类成功！"));
	}
	
	/**
	 * 停用数据
	 */
	@RequiresPermissions("customerclass:customerClass:edit")
	@RequestMapping(value = "disable")
	@ResponseBody
	public String disable(CustomerClass customerClass) {
		CustomerClass where = new CustomerClass();
		where.setStatus(CustomerClass.STATUS_NORMAL);
		where.setParentCodes("," + customerClass.getId() + ",");
		long count = customerClassService.findCount(where);
		if (count > 0) {
			return renderResult(Global.FALSE, text("该客户分类包含未停用的子客户分类！"));
		}
		customerClass.setStatus(CustomerClass.STATUS_DISABLE);
		customerClassService.updateStatus(customerClass);
		return renderResult(Global.TRUE, text("停用客户分类成功"));
	}
	
	/**
	 * 启用数据
	 */
	@RequiresPermissions("customerclass:customerClass:edit")
	@RequestMapping(value = "enable")
	@ResponseBody
	public String enable(CustomerClass customerClass) {
		customerClass.setStatus(CustomerClass.STATUS_NORMAL);
		customerClassService.updateStatus(customerClass);
		return renderResult(Global.TRUE, text("启用客户分类成功"));
	}
	
	/**
	 * 删除数据
	 */
	@RequiresPermissions("customerclass:customerClass:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(CustomerClass customerClass) {
		customerClassService.delete(customerClass);
		return renderResult(Global.TRUE, text("删除客户分类成功！"));
	}
	
	/**
	 * 获取树结构数据
	 * @param excludeCode 排除的Code
	 * @param parentCode 设置父级编码返回一级
	 * @param isShowCode 是否显示编码（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
	 * @return
	 */
	@RequiresPermissions("customerclass:customerClass:view")
	@RequestMapping(value = "treeData")
	@ResponseBody
	public List<Map<String, Object>> treeData(String excludeCode, String parentCode, String isShowCode) {
		List<Map<String, Object>> mapList = ListUtils.newArrayList();
		CustomerClass where = new CustomerClass();
		where.setStatus(CustomerClass.STATUS_NORMAL);
		if (StringUtils.isNotBlank(parentCode)){
			where.setParentCode(parentCode);
		}
		List<CustomerClass> list = customerClassService.findList(where);
		for (int i=0; i<list.size(); i++){
			CustomerClass e = list.get(i);
			// 过滤非正常的数据
			if (!CustomerClass.STATUS_NORMAL.equals(e.getStatus())){
				continue;
			}
			// 过滤被排除的编码（包括所有子级）
			if (StringUtils.isNotBlank(excludeCode)){
				if (e.getId().equals(excludeCode)){
					continue;
				}
				if (e.getParentCodes().contains("," + excludeCode + ",")){
					continue;
				}
			}
			Map<String, Object> map = MapUtils.newHashMap();
			map.put("id", e.getId());
			map.put("pId", e.getParentCode());
			map.put("name", e.getCustomerClassName());
			map.put("title", e.getCustomerClassName());
			map.put("isParent", !e.getIsTreeLeaf());
			mapList.add(map);
		}
		return mapList;
	}

	/**
	 * 修复表结构相关数据
	 */
	@RequiresPermissions("customerclass:customerClass:edit")
	@RequestMapping(value = "fixTreeData")
	@ResponseBody
	public String fixTreeData(CustomerClass customerClass){
		if (!customerClass.currentUser().isAdmin()){
			return renderResult(Global.FALSE, "操作失败，只有管理员才能进行修复！");
		}
		customerClassService.fixTreeData();
		return renderResult(Global.TRUE, "数据修复成功");
	}
	
}